<!-- Created by ctsi-biyi-generator -->
<template>
  <Card>
    <p slot="title">新建字典</p>
    <Form
      ref="formDicType"
      :model="formDicType"
      :rules="ruleValidate"
      :label-width="100"
    >
      <Row :gutter="16" type="flex" justify="space-around">
        <i-col span="9">
            <FormItem label="字典类型" prop="dicType">
              <div >
            <InputNumber
              style="width: 70%"
              v-model="formDicType.dicType"
              placeholder="请输入字典类型"
              :max=10000
            />
            </div>
            </FormItem>
        </i-col>
           <i-col span="9">
          <FormItem label="类型名称" prop="dicTypeName">
            <div >
              <Input
              style="width: 70%"
              v-model.trim="formDicType.dicTypeName"
              placeholder="请输入类型名称"
            />
            </div>
          </FormItem>
        </i-col>
      </Row>
      <Row :gutter="16" type="flex" justify="space-around">
        <i-col span="9">
          <FormItem label="父级名称" prop="dicParentId">
            <div >
              <Input
              :value="showName"
              placeholder="请选择"
              style="width: 70%"
              :readonly="true"
              @click.native="showOrHideTree"
            />
            <div
              v-show="showTree"
              class="treeShow"
              @mouseover="treeShowToggle(1)"
              @mouseout="treeShowToggle(2)"
            >
              <Tree
                :data="treeData"
                @on-select-change="changeCheck"
              />
            </div>
            </div>
          </FormItem>
        </i-col>
        <i-col span="9">
        </i-col>
      </Row>
    </Form>
    <Divider />
    <div style="display:flex;justifyContent:space-between;margin:30px 3% 0 3%">
      <div></div>
      <div style="float: right">
      <Button
            @click="handleCreateOrEditItem()"
            type="primary"
            icon="md-add"
            style="margin: 0 50px"
            >新建</Button
          ></div>
    </div>
    <Row style="margin:5px 3% 0 3%">
      <Col span="24">
        <Table :columns="column" :data="dicData"></Table>
      </Col>

      <!-- <Row type="flex" justify="end" align="middle">
        <div v-if="">
          <Page
          :current="currentPageNum + 1"
          :total="dataCount"
          @on-change="handlePageChange"
          @on-page-size-change="changePage"
          show-elevator
          show-sizer
          show-total
          style="padding: 10px 10px 0 0"
        ></Page>
        </div>
      </Row> -->
    </Row>
    <div style="margin:50px 0 0 45%">
      <Button type="primary" style="marginRight:20px" @click="handleSubmit('formDicType')">提交</Button>
      <Button @click="handleReset('formDicType')">取消</Button>
    </div>
    <Modal
      v-model="show"
      width='30'
      :title="title"
      >
      <Form ref="formDic" :model="formDic" :rules="formDicRule" :label-width="100">
          <FormItem label="字典名称" prop="dicDisplay">
            <Input
              style="width: 85%"
              v-model.trim="formDic.dicDisplay"
              placeholder="请输入字典中文名称"
            />
          </FormItem>

          <FormItem label="排序" prop="dicOrder">
            <InputNumber
              style="width: 85%"
              v-model="formDic.dicOrder"
              placeholder="搜索字典排序"
              :max=1000
            />
          </FormItem>

          <FormItem label="图标" prop="dicIcon">
            <Input
              v-model.trim="formDic.dicIcon"
              placeholder="请输入icon"
              style="width: 85%"
            />
          </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="dicSubmit('formDic')">提交</Button>
        <Button @click="dicCancel('formDic')">取消</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import Util from '@/libs/util.js'

export default {
  data () {
    const validateType = (rule, value, callback) => {
      let arr = this.dicArr
      if (arr.find(item => item === value)) {
        return callback(new Error('此类型已存在'))
      } else {
        return callback()
      }
    }
    const validateDicTypeName = (rule, value, callback) => {
      const [url, httpConfig] = [
        '/api/validation/dicTypeName',
        {
          params: { name: value }
        }
      ]
      if (value !== this.dicTypeName) {
        this.$http.get(url, httpConfig).then(response => {
          if (response.data.code === -1) {
            return callback(new Error(response.data.msg))
          } else {
            return callback()
          }
        }).catch(() => {
          return callback(new Error('异步校验出错！'))
        })
      } else {
        return callback()
      }
    }
    const validateDicDisplay = (rule, value, callback) => {
      if (this.dicDisplay !== value) {
        this.dicData.forEach((item, i, array) => {
          if (value === item.dicDisplay) {
            return callback(new Error('字典名称不能重复！'))
          }
        })
        return callback()
      } else {
        return callback()
      }
    }
    return {
      dicDisplay: null,
      checkData: [],
      showTree: false,
      show: false,
      formDic: {
        dicValue: null,
        dicDisplay: null,
        dicOrder: null,
        dicIcon: null
      },
      dicArr: [],
      formStatus: 'add',
      treeData: [],
      dicData: [],
      dicTypeName: [],
      column: [
        {
          key: 'dicDisplay',
          title: '字典名称'
        },
        {
          key: 'dicOrder',
          title: '排序'
        },
        {
          key: 'dicIcon',
          title: '图标'
        },
        {
          title: '操作',
          width: 155,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.handleCreateOrEditItem(params.row, params.index)
                    }
                  }
                },
                '编辑'
              ),
              h('span', {
                style: {
                  width: '1px',
                  backgroundColor: '#2d8cf0',
                  height: '15px',
                  display: 'inline-block',
                  verticalAlign: 'middle',
                  margin: '-2px 10px 0'
                }
              }),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除这条数据吗?',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      this.deleteDic(params.index)
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        margin: '0 5px'
                      },
                      props: {
                        type: 'error',
                        size: 'small',
                        placement: 'top'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ])
          }
        }
      ],
      formDicType: {
        dicType: null,
        dicTypeName: null,
        dicParentId: null
      },
      formDicRule: {
        dicValue: [
          {
            type: 'number',
            min: 1,
            required: true,
            trigger: 'blur'
          }
        ],
        dicIcon: [
          {
            type: 'string',
            max: 50,
            message: 'icon最多50个字符',
            trigger: 'blur'
          }
        ],
        dicDisplay: [
          {
            required: true,
            message: '字典名称不能为空',
            trigger: 'blur'
          },
          {
            required: true,
            max: 50,
            message: '字典名称最多50个字符',
            trigger: 'blur'
          },
          { validator: validateDicDisplay, trigger: 'blur' }
        ]
      },
      ruleValidate: {
        dicType: [
          {
            type: 'number',
            required: true,
            message: '请填写字典类型。',
            trigger: 'blur'
          },
          {
            trigger: 'change',
            validator: validateType
          }
        ],
        dicTypeName: [
          {
            required: true,
            trigger: 'blur',
            message: '请填写类型名称'
          },
          {
            max: 50,
            message: '字典类型名称最多50个字符',
            trigger: 'blur'
          },
          { validator: validateDicTypeName, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showName: function () {
      let showName = ''
      for (let i = 0; i < this.checkData.length; i++) {
        if (!showName) {
          if (this.checkData[i] !== undefined) {
            showName = this.checkData[i].title
          }
        } else {
          showName = showName + ',' + this.checkData[i].title
        }
      }
      return showName
    },
    title () {
      return this.formStatus == 'add' ? '新建' : '编辑'
    }
  },
  methods: {
    // 初始化树结构
    initTree () {
      Util.http.get('/api/cscpDics/getTree').then((res) => {
        this.treeData = this.setTreeNode(res.data, this.render)
      })
    },

    showOrHideTree () {
      this.showTree = !this.showTree
    },

    treeShowToggle (type) {
      this.showTree = type == 1
    },
    // 新建、编辑
    handleCreateOrEditItem (data, index) {
      if (data) {
        this.formDic = Object.assign({}, data)
        this.formStatus = 'edit'
        this.index = index
        this.dicDisplay = this.formDic.dicDisplay
      } else {
        this.formStatus = 'add'
        this.dicDisplay = null
      }
      this.show = true
    },
    // 取消
    dicCancel (name) {
      this.$refs[name].resetFields()
      this.show = false
    },
    // 添加图标
    setTreeNode (treeData, render) {
      for (let i = 0; i < treeData.length; i++) {
        treeData[i].render = render
        if (treeData[i].children && treeData[i].children.length) {
          this.setTreeNode(treeData[i].children, render)
        }
      }
      return treeData
    },

    render (h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        },
        [
          h('span', [
            h('Icon', {
              props: {
                type: 'ios-folder-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h('span', data.title)
          ])
        ]
      )
    },
    // 选择树数据
    changeCheck (data) {
      this.checkData = data
      this.formDicType.dicParentId = data[0].dicType
      this.showTree = false
    },

    dicSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formStatus === 'add') {
            this.dicData.push(Object.assign({}, this.formDic))
          } else {
            this.dicData.splice(this.index, 1)
            this.dicData.splice(
              this.index,
              0,
              JSON.parse(JSON.stringify(this.formDic))
            )
          }
          this.$refs[name].resetFields()
          this.show = false
        } else {
          // this.$Message.error('提交失败')
        }
      })
    },
    // 提交
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.dicData.length === 0) {
            this.$Message.error('请先添加一条字典数据！')
            return
          }
          let self = this
          this.dicData.forEach(item => {
            item.id = null
            item.dicType = self.formDicType.dicType
            item.dicTypeName = self.formDicType.dicTypeName
            item.dicParentId = self.formDicType.dicParentId
          })
          Util.http
            .post('/api/cscpDics/addLists', self.dicData)
            .then((response) => {
              this.$Message.success('提交成功')
              // self.$router.push({
              //   name: 'paramDic'
              // })
              self.closeMe()
            }
            )
            .catch((e) => {
              console.log(e)
            })
        } else {
          // this.$Message.error('提交失败')
        }
      })
    },

    handleReset (name) {
      this.$refs[name].resetFields()
      // this.$router.push({
      //   name: 'paramDic'
      // })
      this.closeMe()
    },
    closeMe () {
      this.$store.commit('app/closePage', {
        vm: this,
        fromName: this.$route.name,
        toName: 'paramDic'
      })
    },
    // 校验Type不能重复
    initDicList () {
      Util.http.get('/api/cscpDics/getType').then(res => {
        this.dicArr = res.data.map(item => {
          return item.dicType
        })
      })
    },

    deleteDic (index) {
      this.dicData.splice(this.index, 1)
    }
  },
  mounted () {
    this.initTree()
    this.initDicList()
  },
  activated () {

  }
}
</script>
<style scoped>
.treeShow {
  position: absolute;
  z-index: 9999;
  max-height: 300px;
  overflow: auto;
  width: 280px;
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
}
</style>
